
# =============================================================================
# =============================================================================
# Program to calculate some graphs to use in the paper.
# =============================================================================
# =============================================================================

pc = pd.read_parquet(cdd['p_d_pcp'] + r'\pcp.parquet')

# =============================================================================
# Appendix Figure D1: Accuracy of plasma center opening dates
# Plot a histogram of the gap color coded by opening data
cmap = cm.get_cmap('GnBu')
pc['open_g'] = pc['open'].apply(lambda x: '2014-2015' if x<dt.datetime(2016,1,1) else 
                                            ('2016-2017' if x<dt.datetime(2018,1,1) else 
                                            ('2018-2019Q3' if x<dt.datetime(2019,10,1) else '2019Q4-2021')))
pc['gap_s'] = np.round(pc['gap']*3).clip(upper=7)
fig = pc[pc.open>=dt.datetime(2014,1,1)].groupby(['gap_s','open_g']).size().unstack()
fig.index = fig.index.astype(int).map({**{i:i for i in range(7)},**{7:'>6'}})
fig = fig.plot(kind='bar', stacked=True, cmap=cmap, xlabel='Width Opening Window (in quarters)',ylabel='Number of Openings', rot=0)
fig.legend(loc='upper right')
fig.get_figure().savefig(cdd['p_rf'] + r'\General\Appendix Figure D1: OpeningIdentification_v2.png',dpi=300)


# =============================================================================
# Appendix Table B2: Corporations that operate plasma centers
# Group plasma centers by parent corporation and plot over time.
creplace = {'csl':'CSL Plasma','bpl':'BPL Plasma','octa':'Octapharma','octo':'Octapharma','biolife':'Biolife Plasma',
            'biomat ':'Grifols','talec':'Grifols','grifol':'Grifols','gcam':'GCAM Inc.','bpc plasma':'Grifols','biotest':'Grifols',
            'aventis':'Aventis','zlb':'ZLB Plasma','nabi':'Nabi','ked':'KED Plasma','bio life':'Biolife Plasma',
            'alpha':'Grifols','adma':'ADMA BioCenters','plasmacare':'Grifols','interstate blood bank':'Grifols','dci bio':'BPL Plasma',
            'immuno':'Immunotek Bio Centers','bioresou':'Immunotek Bio Centers'
            }
cquery=r'(' + '|'.join(creplace.keys()) + r')'
pc['corp'] = pc['name_corp'].fillna('').apply(lambda x: creplace[re.findall(cquery,x,flags=re.DOTALL|re.IGNORECASE)[0].lower()] if any(re.findall(cquery,x,flags=re.DOTALL|re.IGNORECASE))>0 else '')

parents = {
           'GCAM Inc.':{'Parent':'Green Cross Group','Country':'South Korea','Ticker':'006280 (KRX)'},
           'Grifols':{'Parent':'Grifols S.A.','Country':'Spain', 'Ticker':'GRF (BMAD)'},
           'CSL Plasma':{'Parent':'CSL Ltd.','Country':'Australia','Ticker':'CSL (ASX)'},
           'BPL Plasma':{'Parent':'Creat Group','Country':'China','Ticker':'Private'},
           'Octapharma':{'Parent':'Octapharma AG','Country':'Switzerland','Ticker':'Family Owned'},
           'Biolife Plasma':{'Parent':'Takeda Pharmaceutical','Country':'Japan','Ticker':'TAK (NYSE)'},
           'KED Plasma':{'Parent':'Kedrion Biopharma','Country':'Italy','Ticker':'Private'},
           'ADMA BioCenters':{'Parent':'ADMA Biologics','Country':'USA','Ticker':'ADMA (NASDAQ)'},
           'Immunotek Bio Centers':{'Parent':'N/A','Ticker':'Family Owned','Country':'USA'}              
           }
ptdf = pd.DataFrame(parents).T.reset_index().rename(columns={'index':'Corporation'})
Mergers = [
           {'Predecessor':'Aventis','Successor':'CSL Plasma','Date':dt.datetime(2003,12,9),'fac_acquired':'68 centers','references':['https://en.wikipedia.org/wiki/CSL_Behring','https://www.smh.com.au/national/csl-finally-wraps-up-965m-aventis-purchase-20031210-gdhybu.html','https://www.wsj.com/articles/SB107095001643104600']},
           {'Predecessor':'Nabi','Successor':'CSL Plasma','Date':dt.datetime(2001,9,6),'fac_acquired':'47 centers','reference':['https://www.sun-sentinel.com/news/fl-xpm-2001-06-26-0106250453-story.html']},
           {'Predecessor':'ZLB','Successor':'CSL Plasma','Date':dt.datetime(2000,1,1),'fac_acquired':'Fractation facility','reference':['https://www.cslbehring.ch/en-us/our-company/our-story']},
           {'Predecessor':'Serologicals','Immediate Successor':'Aventis','Successor':'CSL Plasma','Date':dt.datetime(2000,5,1),'fac_acquired':'42 centers','reference':['https://www.cslbehring.ch/en-us/our-company/our-story','https://www.company-histories.com/Serologicals-Corporation-Company-History.html']},
           {'Predecessor':'PlasmaCare','Successor':'Grifols','Date':dt.datetime(2006,3,14),'fac_acquired':'15','reference':['https://www.biospace.com/article/releases/grifols-acquires-15-additional-plasma-collection-centers-through-acquisition-of-b-plasmacare-b-/']},
           {'Predecessor':'Talecris','Successor':'Grifols','Date':dt.datetime(2011,6,1),'fac_acquired':'~74?','reference':['https://www.ftc.gov/sites/default/files/documents/cases/2011/06/110601grifolsaanal.pdf','https://www.grifols.com/documents/51507592/51553926/03_iam-tlc-2010-en.pdf/6df51cd0-440c-48b9-8c5a-4f8f7aae789a']},
           {'Predecessor':'Alpha Therapeutics','Successor':'Grifols','Date':dt.datetime(2004,1,1),'fac_acquired':'','reference':['https://www.grifolsplasma.com/en/about-grifols/timeline-and-history']},
           {'Predecessor':'BPL Plasma','Successor':'Creat Group','Date':dt.datetime(2016,8,1),'fac_acquired':'BPL Therapeutics','reference':['https://en.wikipedia.org/wiki/Bio_Products_Laboratory'],'comment':'Until 2016 it was owned by Bain (80%) and the UK Gov (20%)'},
           {'Predecessor':'Biotest','Successor':'Grifols','Date':dt.datetime(2018,8,8),'fac_acquired':'22','reference':['https://www.biopharma-reporter.com/Article/2018/08/08/Grifols-acquires-Biotest-US-in-286m-deal']},
           {'Predecessor':'BPL','Successor':'Grifols','Date':dt.datetime(2021,3,1),'fac_acquired':'21 centers','reference':['https://www.grifols.com/en/view-news/-/news/grifols-acquires-25-us-based-plasma-centers-from-bpl-ensuring-one-million-additional-liters-for-fractionation']},
           ]

#Create an appendix table with the number of plasma centers active by corporation as of 6/3/2021 date for reference in the main text.
tgtdt = dt.datetime(2021,6,3)
pcs_active_21 = pc[(pc.open<=tgtdt)&(pc.close>=tgtdt)]['mfei'].tolist()
tbl_sum_21 = pc[pc.mfei.isin(pcs_active_21)].groupby('corp')['mfei'].nunique().reset_index().sort_values(by=['mfei'],ascending=0).rename(columns={'mfei':'PCs (2021)','corp':'Corporation'})
tbl_sum_21['Corporation'] = tbl_sum_21['Corporation'].replace('','Other')
tgtdt = dt.datetime(2015,1,30)
pcs_active_15 = pc[(pc.open<=tgtdt)&(pc.close>=tgtdt)]['mfei'].tolist()
tbl_sum_15 = pc[pc.mfei.isin(pcs_active_15)].groupby('corp')['mfei'].nunique().reset_index().rename(columns={'mfei':'PCs (2015)','corp':'Corporation'})
tbl_sum_15['Corporation'] = tbl_sum_15['Corporation'].replace('','Other')
tbl_sum = pd.merge(tbl_sum_15,tbl_sum_21,how='outer',on='Corporation')
tbl_sum = pd.merge(ptdf,tbl_sum,how='outer',on='Corporation').sort_values(by=['PCs (2021)'],ascending=0)
tbl_sum[['PCs (2015)', 'PCs (2021)']] = tbl_sum[['PCs (2015)', 'PCs (2021)']].fillna(0)
tbl_sum[[ 'Parent', 'Country', 'Ticker']] = tbl_sum[[ 'Parent', 'Country', 'Ticker']].fillna('')

#Because of the last row in the Mergers list above where 21 establishments were sold from BPL to Grifols I adjust the table since pcp uses the older establishment operator.
tbl_sum['PCs (2021)'] = tbl_sum['PCs (2021)'] + 21*(tbl_sum['Corporation']=='Grifols') - 21*(tbl_sum['Corporation']=='BPL Plasma')
# my_latex(df=tbl_sum,file=cdd['p_rt'] + r'\General\IndustryComposition.tex',index=False,index_names=False)













